<?php

class FacebookService extends Auth
{
    public $clientId='';
    public $clientSecret='';
    protected $token='';
    protected $userInfo=false, $serviceName='facebook';

    public function getUserInfo()
    {
        $info=$this->userInfo;

        return array(
            'user'=>array(
                'login'=>isset($info->username) ? $info->username : '',
                'userName'=>isset($info->username) ? $info->username : '',
                'password'=>'',
                'confirmCode'=>'',
                'email'=>isset($info->email) ? $info->email : '',
                'isConfirmed'=>1,
                'isActive'=>isset($info->verified) ? $info->verified : 1,
            ),
            'profile'=>array(
                'firstName'=>isset($info->first_name) ? $info->first_name : '',
                'lastName'=>isset($info->last_name) ? $info->last_name : '',
                'sex'=>$info->gender!='male' ? 1 : 0,
                'img'=>isset($info->picture->data->url) ? $info->picture->data->url : '',
            ),
        );
    }

    public function getToken()
    {
        return $this->token;
    }

    public function getServiceName()
    {
        return $this->serviceName;
    }

    public function firstRequest()
    {
        $directUrl='https://www.facebook.com/dialog/oauth?client_id='.$this->clientId.
            '&redirect_uri='.$this->getReturnUrl().'/&scope=email,user_about_me&response_type=code';

        Yii::app()->request->redirect($directUrl);
    }

    public function secondRequest()
    {
        if($code=Yii::app()->request->getQuery('code')){
            $redirectUrl='https://graph.facebook.com/oauth/access_token?client_id='.$this->clientId.
                '&redirect_uri='.$this->getReturnUrl().
                '/&client_secret='.$this->clientSecret.
                '&code='.$code;
            try{
                $result=file_get_contents($redirectUrl);
                parse_str($result,$arrayResult);
                $this->token=$arrayResult['access_token'];

                $redirectUrl='https://graph.facebook.com/me?fields=picture,id,name,username,first_name,last_name,middle_name,gender,link,email,verified&access_token='.$this->token;
                if(is_object($result=json_decode(file_get_contents($redirectUrl)))){
                    if(isset($result->error_msg)) $this->quit($result->error_msg);
                    $this->userInfo=$result;
                    return true;
                }

                return true;
            }catch(Exception $e){
                $this->quit($e);
            }
        }

        return false;
    }
}